import {Component, OnInit} from '@angular/core';
import {FetchService} from "../../../../core/net/fetch.service";
import * as _ from 'lodash';
import * as moment from "moment";
import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'app-wt-lake',
    templateUrl: './wt-lake.component.html',
    styleUrls: ['./wt-lake.component.scss', '../water-takes-report.component.scss']
})
export class WtLakeComponent implements OnInit {

    listData = [];
    frId: string;
    contentTitle: string;
    today: Date = new Date();
    datePicker: Date = new Date();

    tableData = [];
    loading = false;
    basicOpts: any = {
        title: {
            text: "",
            x: "center",
            textStyle: {
                color: "#777",
                fontSize: 16
            }
        },
        color: ['#1ada6f', '#ffbf44', '#12d0d2', '#0092f1', '#ffdc00', '#f9383b'],
        grid: {
            top: '10%',
            left: '8%',
            right: '8%',
            bottom: '12%',
            containLabel: true
        },
        tooltip: {
            trigger: "axis"
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
        },
        yAxis: {
            type: "value"
        }
    };
    customOpts: any = {};
    irrHistoryData = [];
    modaltableData = [];
    modalTitle: string = '湖泊湿地生态补水历史数据';
    modalShow: boolean = false;
    progressModalShow: boolean = false;
    progressData = [];
    reportFinished = 0;
    reportUnfinished = 0;
    reportPercentage = 0;
    lakeTotal = 0;

    constructor(private fetchService: FetchService,
                private http: HttpClient) {
    }

    ngOnInit() {
        this.fetchService.post<any>('muw/wrsMuwFr/list', {type: "3"}).subscribe(res => {
            console.log(res);
            this.listData = res;
            this.selectedAreaChanged(this.listData[0].id);
        });
        this.today = new Date();
        this.getProgressData();
    }
    getProgressData(): void {
        this.fetchService.get<any>('muw/submit/querySubmitLw').subscribe(res => {
            if (res) {
                const group = _.groupBy(res.data, 'statu');
                this.reportFinished = group['2'] ? group['2'].length : 0;
                this.lakeTotal = res.lwValTotal;
                this.reportUnfinished = group['1'] ? group['1'].length : 0;
                this.reportPercentage = res.data.length === 0 ? 0 : Math.round(this.reportFinished / res.data.length * 100);
                res.data.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                });
                this.progressData = _.sortBy(res.data, o => {
                    return o.statu;
                });
            }
        });
    }
    openProgressModal(): void {
        this.progressModalShow = true;
    }
    closeProgressModal() {
        this.progressModalShow = false;
    }
    selectedAreaChanged(id): void {
        this.loading = true;
        const selectedArea = _.find(this.listData, item => {
            return item.id === id;
        });
        this.contentTitle = selectedArea.name;
        this.frId = id;
        const params = {
            frId: id
        };
        this.fetchService.post<any>('muw/wrsMuwLwData/list', params).subscribe(res => {
            this.tableData = _.sortBy(res.wrsMuwLwDatas, o => {
                return o.prId;
            });
            this.selectedRow(this.tableData[0]);
            this.loading = false;
        });
    }

    selectedRow(data): void {
        console.log(data);
        const params = {
            frId: this.frId,
            rrId: data.rrId,
            startDate: moment().subtract(15, 'days').valueOf(),
            endDate: moment().valueOf(),
        };
        this.fetchService.post<any>('muw/wrsMuwLwData/historyDataList', params).subscribe(res => {
            res.forEach(item => {
                item.date = moment(item.time).format("YYYY-MM-DD");
            });
            // result = _.reverse(res);
            this.irrHistoryData = res;
            const xAxisArr = this.irrHistoryData.map(item => {
                return item.date;
            });
            const seriesData = this.irrHistoryData.map(results => {
                return results.wrsMuwLwDatas[0].valTotal;
            });
            this.customOpts = {
                title: {
                    text: `${data.rrName}日补水总量过程曲线`
                },
                xAxis: {
                    data: xAxisArr,
                    axisLabel: {
                        interval: 0
                    }
                },
                yAxis: {
                    name: '补水量(万m³)'
                },
                series: [
                    {
                        name: '补水量',
                        type: 'line',
                        data: seriesData
                    }
                ]
            };
        });

    }

    // getHistoryData(params): Array<any> {
    //     let result = [];
    //     this.fetchService.post<any>('muw/wrsMuwLwData/historyDataList', params).subscribe(res => {
    //         res.forEach(item => {
    //             item.date = moment(item.time).format("YYYY-MM-DD");
    //         });
    //         // result = _.reverse(res);
    //         return res;
    //     });
    //     // return result;
    // }

    openDetailModal(): void {
        this.modalShow = true;
        this.queryInfo(this.today);
    }

    export(): void {
        const param = {
            frId: this.frId ? this.frId : ''
        };
        this.fetchService.export('muw/wrsMuwLwData/export', param).subscribe((res: any) => {
            const blob = new Blob([res], {type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8'});
            const elink = document.createElement('a');

            elink.download = `${this.contentTitle}湖泊湿地补水量.xlsx`;
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        });
    }

    print(): void {
    }

    onCancel() {
        this.modalShow = false;
    }

    queryInfo(date): void {
        const time = moment(date).valueOf();
        const params = {
            frId: this.frId,
            startDate: time,
            endDate: time,
        };
        this.fetchService.post<any>('muw/wrsMuwLwData/historyDataList', params).subscribe(res => {
            if (res) {
                this.modaltableData = _.sortBy(res[0].wrsMuwLwDatas, o => {
                    return o.prId;
                });
            }

        });

    }

    calcRowspan(index, prId): number {
        const firstIndex = _.findIndex(this.tableData, o => {
            return o.prId === prId;
        });
        const lastIndex = _.findLastIndex(this.tableData, o => {
            return o.prId === prId;
        });
        return lastIndex - firstIndex + 1;
    }

    calcColspan(index, prId): number {
        const selectedItem = _.find(this.tableData, o => {
            return o.prId === prId;
        });
        return selectedItem.prName === selectedItem.rrName ? 2 : 1;
    }

    isTdShow(index, prId): boolean {
        const firstIndex = _.findIndex(this.tableData, o => {
            return o.prId === prId;
        });
        const lastIndex = _.findLastIndex(this.tableData, o => {
            return o.prId === prId;
        });
        return index <= firstIndex || index > lastIndex;
    }

    isColTdShow(index, prId): boolean {
        const selectedItem = _.find(this.tableData, o => {
            return o.prId === prId;
        });
        return selectedItem.prName !== selectedItem.rrName;
    }
}
